package com.sx.core.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesUtil {

    public static void main(String args[]) throws Exception {
        /**
         * 加密用的Key 可以用26个字母和数字组成，最好不要用保留字符，
         * 虽然不会错，至于怎么裁决，个人看情况而定
         *
         * key == AppSecret
         */
//        String cKey = "1234567890123456";
//        // 需要加密的字串
//        String cSrc = "{\"code\":\"0\",\"error_msg\":\"密码错误\",\"weixiao_openid\":\"12345678\",\"student_num\":\"888888888888\",\"name\":\"洪丹丹测试\",\"sign\":\"5C6E844C23C8F0C15AF382081D0663DC\"}";
//        // app_secret 取前16位;
//        String cIv = "0123456789123456";
//        System.out.println(cSrc);
//        // 加密
//        long lStart = System.currentTimeMillis();
//        String enString = AesUtil.Encrypt(cSrc, cKey, cIv);
//        System.out.println("加密后的字串是：" + enString);
//
//        long lUseTime = System.currentTimeMillis() - lStart;
//        System.out.println("加密耗时：" + lUseTime + "毫秒");
//        // 解密
//        lStart = System.currentTimeMillis();
//        String DeString = AesUtil.Decrypt(enString, cKey, cIv);
//        System.out.println("解密后的字串是：" + DeString);
//        lUseTime = System.currentTimeMillis() - lStart;
//        System.out.println("解密耗时：" + lUseTime + "毫秒");
//        System.out.println("解密耗时：" + lUseTime + "毫秒");
//        System.out.println("解密耗时：" + lUseTime + "毫秒");
//        System.out.println(new String(Hex.decodeHex("B9E3D6DDCAA2BEE6D6C7C4DCBFC6BCBC".toCharArray())));
//        System.out.println(EncryptECB(Hex.decodeHex(" 10 00 12 0B 07 12 1B 01 54 67 96 B6 00 00 00 00".replaceAll(" ","").toCharArray()),Hex.decodeHex("B9E3D6DDCAA2BEE6D6C7C4DCBFC6BCBC".toCharArray()),"0123456789123456"));
//        System.out.println(" 10 00 12 0B 07 12 1B 01 54 67 96 B6 00 00 00 00".replaceAll(" ",""));
//        67059f14d0345005db83b29fc3653f32


        String src="123k开导开导";
        String key= "B9E3D6DDCAA2BEE6D6C7C4DCBFC6BCBC";
        String iv= "0123456789123456";
        String en=EncryptECB(src,key,iv);
        System.out.println("en=="+en);
        String de=DecryptECB(en,key,iv);
        System.out.println("de=="+de);



    }

    /**
     * 加密
     * @param sSrc 需要加密的字符串
     * @param sKey 加密key
     * @param sIv 加密随机字符串
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc, String sKey, String sIv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        byte[] dataBytes = sSrc.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }
        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        SecretKeySpec keyspec = new SecretKeySpec(sKey.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(sIv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);
        return byte2hex(encrypted).toLowerCase();
    }
     public static String EncryptECB(String sSrc, String sKey,String sIv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        byte[] dataBytes = sSrc.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }
        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        SecretKeySpec keyspec = new SecretKeySpec(sKey.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(sIv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, keyspec,ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);
        return byte2hex(encrypted);
    }
    /**
     * 解密
     * @param sSrc 需要解密的字符串
     * @param sKey 密钥
     * @param sIv
     * @return
     * @throws Exception
     */
    public static String DecryptECB(String sSrc, String sKey,String sIv) throws Exception {
        byte[] encrypted1      = hex2byte(sSrc);
        Cipher cipher          = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keyspec  = new SecretKeySpec(sKey.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(sIv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keyspec,ivspec);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString;
    }
    /**
     * 解密
     * @param sSrc 需要解密的字符串
     * @param sKey 密钥
     * @param sIv
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc, String sKey, String sIv) throws Exception {
        byte[] encrypted1      = hex2byte(sSrc);
        Cipher cipher          = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keyspec  = new SecretKeySpec(sKey.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(sIv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString;
    }


    public static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
                    16);
        }

        return b;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }

        return hs.toUpperCase();
    }
}
